package com.dongan.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.dongan.pojo.*;
import com.dongan.service.DesignProcedureDetailsService;
import com.dongan.service.DesignProcedureModuleService;
import com.dongan.service.DesignProcedureService;
import com.dongan.service.ModuleDetailsService;
import com.dongan.utils.ResultResponseUtil;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.type.ReferenceType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 生产工序物料明细
 *
 * @author longTao
 * @since 2021-06-15
 */
@RestController
@RequestMapping("/design-procedure-module")
@CrossOrigin
public class DesignProcedureModuleController {
    @Autowired
    private DesignProcedureService procedureService;
    @Autowired
    private ModuleDetailsService moduleDetailsService;
    @Autowired
    private DesignProcedureModuleService service;
    @Autowired
    private DesignProcedureDetailsService procedureDetailsService;
    /**
     * 根据工序详细编号
     * @param procedureDetailId
     * @return
     */
    @GetMapping("/queryByProcedureDetailId")
    @PreAuthorize("hasAuthority('/processMaterialDesignSheetQuery')")
    public Object queryByProcedureDetailId(String procedureDetailId){
        QueryWrapper<DesignProcedureModule> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("PARENT_ID",procedureDetailId);
        List<DesignProcedureModule> procedureModules=service.list(queryWrapper);
        if(procedureModules==null){
            return new ResultResponseUtil(false,"ERROR!");
        }
        return new ResultResponseUtil(true,"查询成功!",procedureModules);
    }
    /**
     * 根据产品编号获取物料明细
     * @param productId
     * @return
     */
    @GetMapping("/queryModuleDetailByProductId")
    @PreAuthorize("hasAuthority('/processMaterialDesignSheetQuery')")

    public Object queryModuleDetailByProductId(String productId){

        List<ModuleDetails> moduleDetails=moduleDetailsService.queryModuleDetailByProductId(productId);
        System.out.println("经过了方法");
        if(moduleDetails==null){
            System.out.println("list为null");
            return new ResultResponseUtil(false,"产品物料组成设计未成为!");
        }
        return new ResultResponseUtil(true,"查询成功!",moduleDetails);
    }
    /**
     * 工序物料设计
     * @param map
     * @return
     */
    @PostMapping("/addProcedureModule")
    @PreAuthorize("hasAuthority('/developProcessMaterialDesignSheet')")
    public Object addProcedureModule(@RequestBody Map<String,Object> map){
        List<ModuleDetails> moduleDetails=null;
        List<DesignProcedureModule> procedureModules=null;
        String procedureDetailId=null;
        ObjectMapper mapper=new ObjectMapper();
        try {
            moduleDetails=mapper.readValue(mapper.writeValueAsString(map.get("moduleDetails")), new TypeReference<List<ModuleDetails>>() {
            });
            procedureModules=mapper.readValue(mapper.writeValueAsString(map.get("procedureModules")), new TypeReference<List<DesignProcedureModule>>() {
            });
            procedureDetailId=(mapper.writeValueAsString(map.get("procedureDetailId"))).substring(1,mapper.writeValueAsString(map.get("procedureDetailId")).length()-1);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        BigDecimal sum=new BigDecimal(0);
        for (DesignProcedureModule procedureModule : procedureModules) {
            //工序详细编号
            procedureModule.setParentId(Long.valueOf(procedureDetailId));
            //小计
            procedureModule.setSubtotal(procedureModule.getAmount().multiply(procedureModule.getCostPrice()));
            sum=sum.add(procedureModule.getSubtotal());

            for (ModuleDetails moduleDetail : moduleDetails) {
                if (moduleDetail.getProductId().equals(procedureModule.getProductId()) && procedureModule.getAmount().compareTo(BigDecimal.ZERO)>0){
                    BigDecimal amount=BigDecimal.valueOf(moduleDetail.getResidualAmount()).subtract(procedureModule.getAmount());
                    moduleDetail.setResidualAmount(amount.longValue());
                    moduleDetailsService.updateById(moduleDetail);
                }
            }

        }
        //插入工序物料详情
        boolean flag=service.saveBatch(procedureModules);
        //工序详情修改
        DesignProcedureDetails procedureDetails=new DesignProcedureDetails();
        procedureDetails.setId(Long.valueOf(procedureDetailId));
        procedureDetails.setModuleSubtotal(sum);
        procedureDetails.setDesignModuleTag("D002-1");
        boolean flag2=procedureDetailsService.updateById(procedureDetails);
        if(flag&&flag2){
            return new ResultResponseUtil(true,"设计成功!");
        }
        return new ResultResponseUtil(false,"设计失败!");
    }
    /**
     * 删除工序物料设计
     * @param map
     * @return
     */
    @PostMapping("/deleteProcedureModule")
    @PreAuthorize("hasAuthority('/processMaterialDesignSheetQuery')")
    public Object deleteProcedureModule(@RequestBody Map<String,Object> map){
        List<DesignProcedureModule> procedureModules=null;
        String productId="";
        String tag="";
        ObjectMapper mapper=new ObjectMapper();
        try {
            procedureModules=mapper.readValue(mapper.writeValueAsString(map.get("procedureModules")), new TypeReference<List<DesignProcedureModule>>() {
            });
            productId=mapper.writeValueAsString(map.get("productId")).substring(1,mapper.writeValueAsString(map.get("productId")).length()-1);
            tag=mapper.writeValueAsString(map.get("tag"));
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        List<Long> pmIds=new ArrayList<>();
        List<ModuleDetails> moduleDetails=moduleDetailsService.queryModuleDetailByProductId(productId);
        //物料详情修改
        for (DesignProcedureModule procedureModule : procedureModules) {
            pmIds.add(procedureModule.getId());
            for (ModuleDetails moduleDetail : moduleDetails) {
                if (moduleDetail.getProductId().equals(procedureModule.getProductId()) && procedureModule.getAmount().compareTo(BigDecimal.ZERO)>0){
                    BigDecimal amount=BigDecimal.valueOf(moduleDetail.getResidualAmount()).add(procedureModule.getAmount());
                    moduleDetail.setResidualAmount(amount.longValue());
                    moduleDetailsService.updateById(moduleDetail);
                }
            }
        }

        boolean flag=service.removeByIds(pmIds);
        //工序详情修改
        DesignProcedureDetails procedureDetails=new DesignProcedureDetails();
        procedureDetails.setId(procedureModules.get(0).getParentId());
        procedureDetails.setDesignModuleTag("D002-0");
        if("".equals(tag)){
            procedureDetails.setDesignModuleChangeTag("D003-1");
        }
        boolean flag2=procedureDetailsService.updateById(procedureDetails);
        if(flag&&flag2){
            return new ResultResponseUtil(true,"删除成功!");
        }
        return new ResultResponseUtil(false,"删除失败!");
    }

    /**
     * 审核
     * @param map
     * @return
     */
    @PostMapping("checkProcedureModule")
    @PreAuthorize("hasAuthority('/processMaterialDesignSheetReview')")
    public Object checkProcedureModule(@RequestBody Map<String ,Object> map){
        DesignProcedure procedures=null;
        List<DesignProcedureDetails> procedureDetails=null;
        ObjectMapper mapper=new ObjectMapper();
        try {
            procedures=mapper.readValue(mapper.writeValueAsString(map.get("procedures")),DesignProcedure.class);
            procedureDetails=mapper.readValue(mapper.writeValueAsString(map.get("procedureDetails")), new TypeReference<List<DesignProcedureDetails>>() {
            });
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        //DESIGN_MODULE_TAG	VARCHAR2(20)	工序物料设计标志
        //G002-0: 未设计
        //G002-2: 已审核
        if("G002-0".equals(procedures.getDesignModuleTag())){
            //审核不通过 设置为未设计
            boolean flag=procedureService.updateById(procedures);
            //工序详情
            for (DesignProcedureDetails procedureDetail : procedureDetails) {
                //未设计工序物料
                procedureDetail.setDesignModuleTag("D002-0");
                procedureDetailsService.updateById(procedureDetail);
                //删除工序物料详细
                QueryWrapper<DesignProcedureModule> queryWrapper2=new QueryWrapper<>();
                queryWrapper2.eq("PARENT_ID",procedureDetail.getId());
                service.remove(queryWrapper2);
            }
            //物料详情修改可用数量
            List<ModuleDetails> moduleDetails=
                    moduleDetailsService.queryModuleDetailByProductId(procedures.getProductId());
            for (ModuleDetails moduleDetail : moduleDetails) {
                moduleDetail.setResidualAmount(moduleDetail.getAmount());
            }
            moduleDetailsService.updateBatchById(moduleDetails);
            return new ResultResponseUtil(true,"审核完成!");
        }else if("G002-2".equals(procedures.getDesignModuleTag())){
            //审核通过
            boolean flag=procedureService.updateById(procedures);
            return new ResultResponseUtil(flag,"审核完成!");
        }

        return new ResultResponseUtil(false,"审核失败!");
    }

}

